package com.demo.blog;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo.util.Lang;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.upload.UploadFile;

/**
 * BlogController
 * 所有 sql 与业务逻辑写在 Model 或 Service 中，不要写在 Controller 中，养成好习惯，有利于大型项目的开发与维护
 */
@Before(BlogInterceptor.class)
public class BlogController extends Controller {
	
	static Prop prop = PropKit.use("a_little_config.txt");
	public void index() {
		setAttr("blogPage", Blog.me.paginate(getParaToInt(0, 1), 10));
		render("blog.html");
	}
	
	public void add() {
	}
	
	@Before(BlogValidator.class)
	public void save() {
		getModel(Blog.class).save();
		redirect("/blog");
	}
	
	public void edit() {
		setAttr("blog", Blog.me.findById(getParaToInt()));
	}
	
	@Before(BlogValidator.class)
	public void update() {
		getModel(Blog.class).update();
		redirect("/blog");
	}
	
	public void delete() {
		Blog.me.deleteById(getParaToInt());
		redirect("/blog");
	}
	
	public void uploadify(){
		renderJsp("upload.jsp");
	}
	
	public void jqupload(){
		renderJsp("jqupload.jsp");
	}
	public void test(){
		List<UploadFile> list = getFiles("temp");
		String index1 = getPara("index1", "default");
		String index2 = getPara("index2", "default");
		
		String prefix = prop.get("path.prefix");
		String domain = prop.get("static.domain");
		
		String dir = prefix+index1+"/"+index2+"/";
		String url = domain+index1+"/"+index2+"/";
		JSONArray jsonArray = new JSONArray();
		for(UploadFile file:list) {
			String fileName = file.getFileName();
			String[] array = fileName.split("\\.");
			String suffix = array[array.length-1];
			String newName = Lang.getUUID()+"."+suffix;;
			String path = dir+newName;
			url = url+newName;
			File target = new File(path);
			JSONObject json = new JSONObject();
			try {
				FileUtils.moveFile(file.getFile(), target);
				json.put("name", file.getParameterName());
				json.put("url", url);
				jsonArray.add(json);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		renderJson(jsonArray.toString());
	}
}


